package com.fly.exception;

import com.fly.vo.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;


/**
 * 全局异常处理
 * @author Fly
 * @Description
 * @Date Created in 8:43 2017/9/12
 * @Modified by
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LogManager.getLogger(this.getClass());
    /**
     * 自定义抛出异常处理
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public Response jsonErrorHandler(MyException e) throws Exception {
        Response response = new Response(false,e.getMessage());
        return response;
    }

    /**
     * 校验异常处理
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseBody
    public Response constraintViolationHandler(ConstraintViolationException e) throws Exception {
        List<String> msgList = new ArrayList<>();
        for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
            msgList.add(constraintViolation.getMessage());
        }
        String messages = StringUtils.join(msgList.toArray(), ";");
        Response response = new Response(false,messages);
        return response;
    }


    /**
     * 其他异常处理
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Response errorHandler(Exception e) throws Exception{
        e.printStackTrace();
        logger.error("发生异常:" + e.getMessage());
        return new Response(false,"处理失败");
    }

}
